package top.rainbowecho.common.mq;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.AsyncRabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import top.rainbowecho.common.mq.config.MqConfiguration;

/**
 * @author rainbow
 * @since 2019/12/6 13:24
 */
@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties(MqConfiguration.class)
@ComponentScan("top.rainbowecho.common.mq.config")
public class RabbitConfiguration {

    @Bean
    public Jackson2JsonMessageConverter jackson2JsonMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }

    @Bean
    public AsyncRabbitTemplate asyncRabbitTemplate(RabbitTemplate rabbitTemplate, Jackson2JsonMessageConverter messageConverter) {
        rabbitTemplate.setMessageConverter(messageConverter);

        AsyncRabbitTemplate asyncRabbitTemplate = new AsyncRabbitTemplate(rabbitTemplate);

        // 开启confirm和return机制
        asyncRabbitTemplate.setMandatory(true);
        asyncRabbitTemplate.setEnableConfirms(true);

        return asyncRabbitTemplate;
    }
}
